package com.ideaaedi.commonds.exception;

import com.ideaaedi.commonds.io.IOUtil;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
public class ExceptionUtil {
    
    /**
     * 将异常堆栈 信息 转换为字符串
     *
     * @param e
     *            异常
     * @return 该异常的错误堆栈信息
     */
    public static String getStackTraceMessage(Throwable e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将异常的的堆栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
            return sw.toString();
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        } finally {
            IOUtil.close(pw, sw);
        }
    }
    
    /**
     * 从异常链中直接寻找toSearchThrowable异常
     *
     * @param throwable 暴露异常（Nullable）
     * @param toSearchThrowable 要寻找的异常（NonNull）
     * @param depth 向下寻找深度（throwable本身不计数）
     *
     * @return 异常T (null-则表示未找到)
     */
    public static <T extends Throwable> T extractThrowable(Throwable throwable, Class<T> toSearchThrowable, int depth) {
        if (throwable == null) {
            return null;
        }
        if (toSearchThrowable.isAssignableFrom(throwable.getClass())) {
            return (T)throwable;
        }
        if (depth <= 0) {
            return null;
        }
        Throwable cause = throwable.getCause();
        T t = null;
        for (int i = 0; i < depth; i++) {
            if (cause == null) {
                break;
            }
            if (toSearchThrowable.isAssignableFrom(cause.getClass())) {
                t = (T)cause;
                break;
            }
            cause = cause.getCause();
        }
        return t;
    }
}